import React from 'react';
import { SearchBar } from 'antd-mobile';
import { Helmet } from 'react-helmet';
import styles from './MyTasksContentPage.less';
import { connect } from 'dva';
import moment from "moment/moment";
import classnames from 'classnames';
import { routerRedux } from "dva/router";

class MyTasksContentPage extends React.Component {

  state = {
    sort: '',
  }

  componentWillMount() {
    //if (this.props.location.action==='PUSH') {
      this.fetch(undefined,1);
    //}
  }

  componentDidMount() {
    const itemName = 'myTasksContent' + this.props.location.query.type;
    const str = sessionStorage.getItem(itemName) || '';
    const arr = str.split('#');
    this.setState({
      sort: arr[0].length ? arr[0] : this.timeSort()[1],
    });
    if (arr[1]) {
      window.scrollTo(0, arr[1]);
    }
  }

  componentWillUnmount() {
    const str = `${this.state.sort}#${document.body.scrollTop || document.documentElement.scrollTop}`;
    const itemName = 'myTasksContent' + this.props.location.query.type;
    sessionStorage.setItem(itemName, str);
  }

  fetch = (key, firstPage) => {
    const { type, isBranch } = this.props.location.query;
    const { dispatch } = this.props;
    const { branchPickerValue } = this.props.stat;
    const startDate = moment(branchPickerValue[1]).startOf('month').format('YYYY-MM-DD');
    const endDate = moment(branchPickerValue[1]).add(1, 'months').startOf('month').format('YYYY-MM-DD');

    // 待回访
    if (type === '1') {
      dispatch({
        type: 'task/fetchMyTasks',
        payload: { complete: 0, tasks: 'tasks1', key, firstPage, startDate, endDate, isBranch },
      });
    }
    // 已回访
    else if (type === '2') {
      dispatch({
        type: 'task/fetchMyTasks',
        payload: { complete: 1, tasks: "tasks2", key, firstPage, startDate, endDate, isBranch },
      });
    }
    // 转化成功
    else if (type === '3') {
      dispatch({
        type: 'task/fetchMyTasks',
        payload: { success: true, tasks: "tasks3", key, firstPage, startDate, endDate, isBranch },
      });
    }
    // 已过期
    else if (type === '4') {
      dispatch({
        type: 'task/fetchMyTasks',
        payload: { isExpired: true, tasks: "tasks4", key, firstPage, startDate, endDate, isBranch },
      });
    }
    // 应回访
    else if (type === '5') {
      dispatch({
        type: 'task/fetchMyTasks',
        payload: { tasks: "tasks5", key, firstPage, startDate, endDate, isBranch },
      });
    }
  }

  timeSort = () => {
    const { type } = this.props.location.query;
    if (type === '1' || type === '5') {
      return ['推送时间', 'createAt'];
    } else if (type === '2') {
      return ['回访时间', 'updateAt'];
    } else if (type === '3') {
      return ['转化时间', 'updateAt'];
    } else if (type === '4') {
      return ['过期时间', 'createAt'];
    }
  }

  sortData = (data) => {
    let arr = data;
    const { sort } = this.state;
    if (sort === this.timeSort()[1]) {
      arr = data.sort((a, b) => (b[sort] || '').localeCompare(a[sort] || ''));
    } else if (sort === 'level') {
      arr = data.sort((a, b) => (a[sort] || 'E').localeCompare(b[sort] || 'E'));
    } else if (sort === 'money') {
      arr = data.sort((a, b) => (b[sort] || 0) - (a[sort] || 0));
    }
    return arr;
  }

  changeSort = (sort) => {
    this.setState({
      sort,
    });
  }

  onSubmit = (value) => {
    this.fetch(value, true);
  };

  title = () => {
    const { type } = this.props.location.query;
    if (type === '1') {
      return '待回访客户数';
    } else if (type === '2') {
      return '实际回访客户数';
    } else if (type === '3') {
      return '转化成功客户数';
    } else if (type === '4') {
      return '过期任务数';
    } else if (type === '5') {
      return '应回访客户数';
    }
  }

  getTypeLabel = (type) => {
    switch (type) {
      case 0:
        return '新客转化';
      case 1:
        return '复购提醒';
      case 2:
        return '转惯';
      case 3:
        return '沉睡唤醒';
      case 4:
        return '流失挽回';
      case 5:
        return '成长关怀';
      case 6:
        return '奶粉升阶';
      case 7:
        return '纸尿裤升码';
      case 8:
        return '新客回头';
      case 9:
        return '新客转惯';
      case 10:
        return '老客复购';
      case 101:
        return '定制任务';
      case 12:
        return '疫苗提醒';
      case 13:
        return '奶粉提醒';
      case 14:
        return '纸尿裤提醒';
      case 15:
        return '老客关怀';
      case 16:
        return '入会关怀';

    }
  };

  getWayLabel = (way) => {
    switch (way) {
      case 1:
        return '电话';
      case 2:
        return '短信';
      case 3:
        return '微信';
      default:
        return '电话';
    }
  };

  vipImg = (type) => {
    switch (type) {
      case 'A':
        return require("../assets/vipA.png");
      case 'B':
        return require("../assets/vipB.png");
      case 'C':
        return require("../assets/vipC.png");
      case 'D':
        return require("../assets/vipD.png");
      case 'E':
        return require("../assets/vipD.png");
      case 'F':
        return require("../assets/vipC.png");
      default:
        return require("../assets/vipD.png");
    }
  };

  getVipType = (type) => {
    switch (type) {
      case 'A':
        return '核心会员';
      case 'B':
        return '忠诚会员';
      case 'C':
        return '普通会员';
      case 'D':
        return '低效会员';
      case 'E':
        return '流失会员';
      case 'F':
        return '新注册会员';
      default:
        return '流失会员';
    }
  };

  vipColor = (type) => {
    switch (type) {
      case 'A':
        return styles.hx;
      case 'B':
        return styles.zc;
      case 'C':
        return styles.pt;
      case 'D':
        return styles.dx;
      case 'E':
        return styles.dx;
      case 'F':
        return styles.pt;
      default:
        return styles.dx;
    }
  };

  pushURL = (data) => {
    const query = { cardNo: data.card_no,cardId:data.card_id, taskType: data.type };
    if (data.subType) {
      query.subType = data.subType;
    }
    query.title = '会员详情';
    this.props.dispatch(routerRedux.push({
      pathname: '/p1_info',
      query,
    }));
  }

  render() {
    const { type } = this.props.location.query;
    const key = `tasks${type}`;
    let data = this.props.task[key] ? this.props.task[key].data : [];
    const meta = this.props.task[key] ? this.props.task[key].meta : {};
    const { sort } = this.state;
    data = this.sortData(data);
    return (
      <div>
        <Helmet>
          <title>
            {this.title()}
          </title>
        </Helmet>
        <div className={styles.bgInput}>
          <SearchBar placeholder="请输入会员手机号码或姓名" onSubmit={this.onSubmit} />
        </div>
        <div className={styles.flex}>
          <div
            onClick={this.changeSort.bind(this, this.timeSort()[1])} className={classnames({
              [styles.one]: true,
              [styles.active]: sort === this.timeSort()[1],
            })}
          >{this.timeSort()[0]}排序
          </div>
          {
            type === '3' &&
            <div
              onClick={this.changeSort.bind(this, 'money')} className={classnames({
                [styles.one]: true,
                [styles.active]: sort === 'money',
              })}
            >转化金额排序
            </div>
          }
          <div
            onClick={this.changeSort.bind(this, 'level')} className={classnames({
              [styles.one]: true,
              [styles.active]: sort === 'level',
            })}
          >会员类型排序
          </div>
        </div>
        <div className={styles.bgWhite}>
          {
            data.map((item, index) => (
              <div key={index} className={styles.section} onClick={this.pushURL.bind(this, item)}>
                <div className={styles.flex1}>
                  <div className={styles.left}>
                    <span className={styles.name}>{item.vip_name}</span>
                    <img className={styles.vipImg} src={this.vipImg(item.level)} alt="" />
                    <span className={this.vipColor(item.level)}>
                      {this.getVipType(item.level)}
                    </span>
                  </div>
                  {
                    type === '2' &&
                    <div className={styles.right}>
                      回访时间：{moment(item.updateAt).format('YYYY-MM-DD')}
                    </div>
                  }
                </div>
                <div className={styles.flex1}>
                  <div className={[styles.left, styles.task].join(' ')}>
                    任务类型：{this.getTypeLabel(item.type)}
                  </div>
                  {
                    type === '2' &&
                    <div className={styles.right}>
                      回访方式：{this.getWayLabel(item.way)}
                    </div>
                  }
                  {
                    type === '3' &&
                    <div className={[styles.right, styles.money].join(' ')}>
                      ￥{Number(item.money).toFixed(2)}
                    </div>
                  }
                  {
                    (type === '4') &&
                    <div className={styles.right}>
                      过期时间：{moment(item.expireAt).utc().format('YYYY-MM-DD')}
                    </div>
                  }
                  {
                    (type === '1' || type === '5') &&
                    <div className={styles.right}>
                      推送时间：{moment(item.createAt).format('YYYY-MM-DD')}
                    </div>
                  }
                </div>
              </div>
            ))
          }

          {
            meta.page < meta.totalPageCount ?
              <div
                className={styles.nextPage} onClick={() => {
                  this.fetch();
                }}
              >下一页</div> :
              <div className={styles.nextPage}>已全部加载完</div>
          }
        </div>
      </div>
    );
  }
}

export default connect(({ task, stat }) => ({ task, stat }))(MyTasksContentPage);
